package com.hyh.toyshopping.controller;

import com.hyh.toyshopping.commons.Result;
import com.hyh.toyshopping.exceptions.PasswordException;
import com.hyh.toyshopping.exceptions.UsernameNotFoundException;
import com.hyh.toyshopping.model.Admin;
import com.hyh.toyshopping.model.param.LoginParam;
import com.hyh.toyshopping.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @BelongsProject:IntelliJ IDEA
 * @BelongsPackage:com.hyh.toyshopping.controller
 * @Author:hyhWTX
 * @ClassName:AdminController
 * @CreateTime:2022年-12月-15日 12:52
 * @Description: TODO (一句话描述以下该类的功能)
 */
@RestController
@RequestMapping("/manager/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    /**
     * 用户登录
     * @RequestBody:请求体注解，它会自动将请求中的"payload"参数封装到指定的对象中
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam, HttpSession session){

        try {
            try {
                //休眠
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }





            Admin admin = adminService.login(loginParam);
            if(admin!=null){
                //将当前账户对象存入到session中
                session.setAttribute("admin",admin);
            }
            //封装为一个Result对象并返回
            return Result.success("登录成功",admin);
        } catch (UsernameNotFoundException e) {
            e.printStackTrace();
            //生成一个Result对象并返回
            return Result.fail(500,e.getMessage());
        } catch (PasswordException e) {
            e.printStackTrace();
            //生成一个Result对象并返回
            return Result.fail(500,e.getMessage());
        }
    }


    /**
     * 用户退出
     * @param session
     * @return
     */
    @DeleteMapping("/exit")
    public Result exit(HttpSession session){
        session.invalidate();//销毁session对象
        return Result.success("退出成功");
    }
}
